package com.hsck.order.kds.base.common

import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.hsck.order.kds.R

/**
 * 创建者 : ly
 * 时间 : 2017/9/13
 * 公司 : 工博
 * 功能 :ImageView延展
 */
object ScaleType {
    const val CenterCrop = "CenterCrop"
    const val CircleCrop = "CircleCrop"
    const val FitCenter = "FitCenter"
    const val CircularBead = "CircularBead"
}

fun ImageView.loadUrl(
    url: String? = "",
    isCache: Boolean = true,
    scaleType: String = ScaleType.CenterCrop,
    roundedCorners: Int = 8,
    type: Int = 0
) {
    var imgUrl = url
    if (url == null) {
        imgUrl = ""
    }
    Glide.with(context).load(imgUrl).apply(
        RequestOptions()
            .getScaleTypeRequestOptions(scaleType, roundedCorners)
            .getCacheRequestOptions(isCache, type)
    ).into(this)


}

fun RequestOptions.getScaleTypeRequestOptions(
    scaleType: String,
    roundedCorners: Int
): RequestOptions {
    return when (scaleType) {
        ScaleType.CenterCrop -> {
            centerCrop()
        }

        ScaleType.CircleCrop -> {
            circleCrop()
        }

        ScaleType.FitCenter -> {
            fitCenter()
        }

        ScaleType.CircularBead -> {
//            centerCrop()
//           centerCrop.transfor
            centerCrop().transform(RoundedCorners(roundedCorners))

        }

        else -> {
            this
        }
    }
}

fun RequestOptions.getCacheRequestOptions(isCache: Boolean, type: Int = 0): RequestOptions {
    return if (isCache) {
        if (type == 0) {
            placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .skipMemoryCache(false)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .dontAnimate()//取消Glide自带的动画
        } else {
            placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .skipMemoryCache(false)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .dontAnimate()//取消Glide自带的动画
        }

    } else {
        skipMemoryCache(false)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
    }
}


fun ImageView.loadPath(path: String, isCache: Boolean = true) {
    if (isCache) {
        Glide.with(context).load(path).into(this)
    } else {
        Glide.with(context).load(path).apply(getRequestOptions()).into(this)
    }
}

fun ImageView.loadAdUrl(url: String) {
    Glide.with(context).load(url)
        .apply(RequestOptions().centerCrop()).into(this)
}


fun getRequestOptions(): RequestOptions {
    var options = RequestOptions()
    options.centerCrop()//图片显示类型
    options.skipMemoryCache(false)//禁用缓存,包括内存和磁盘
    options.diskCacheStrategy(DiskCacheStrategy.NONE)//仅跳过磁盘缓存
    return options
}




